package com.mashibing.juc.c_019;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 本质上就是共享锁和排他所
 * 读锁就是共享锁（所有线程都可以一起读）
 * 写锁就是排它锁(一个线程在写的时候，其他线程不能写)
 * @author: Yuanzt
 * @Date: 2021/3/26
 */
public class T10_TestReadWriteLock {

    static Lock lock = new ReentrantLock();

    private static int value;
    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();

    public static void read(Lock lock){
        try {
            lock.lock();
            Thread.sleep(1000);
            System.out.println("read over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock ,int v){
        try {
            lock.lock();
            Thread.sleep(1000);
            value = v;
            System.out.println("write over");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
//        Runnable readR   = ()-> read(lock);
        /*如果不读线程不加锁，会出现脏读的情况*/
        Runnable readR   = ()-> read(readLock);
//        Runnable writeR = ()->write(lock,new Random().nextInt());
        Runnable writeR = ()->write(writeLock,new Random().nextInt());
        for (int i = 0; i < 18; i++) new Thread(readR).start();
        for (int i = 0; i < 2; i++) new Thread(writeR).start();
    }

}
